Analysis of differences between global variables global and $GLOBALS[] in PHP

  • 2020-05-19 04:20:08
  • OfStack

1. Compare with examples
Case 1:
 
<?php 
$var1 = 1; 
function test(){ 
unset($GLOBALS['var1']); 
} 
test(); 
echo $var1; 
?> 

Because $var1 was deleted, nothing was printed.
Example 2:
 
<?php 
$var1 = 1; 
function test(){ 
global $var1; 
unset($var1); 
} 
test(); 
echo $var1; 
?> 

Accidentally printed a 1. Prove that only the alias reference has been removed and its own value has not been changed in any way.

2. Explain
global $var is just &$GLOBALS['var'], which calls the 1 name of the external variable.
The $var1 and $GLOBALS['var1'] in the code above refer to the same variable, not two different variables.
PHP has a slightly different global variable than C. In C, global variables are active in functions unless they are shrouded by local variables. This can cause some problems, and some people may inadvertently switch to a global variable. Global variables in PHP must be declared as global when applied in a function using global.
The Global variable of PHP is used to define a global variable, but this global variable is not applied to the entire website, but to the current page, including all files of include or require.

Conclusion 3.
1.$GLOBALS['var'] is the external global variable itself
2.global $var is a reference or pointer to the external $var with the same name.

Related articles: